import { defineStore } from 'pinia'
import { ref,computed } from 'vue'
export const useAuthStore = defineStore('auth', () =>{
    let _token = ref({})
    let _user = ref('')
    function setUserToken(user,token){
        // 保存到对象（内存中）
        _token.value = token
        _user.value = user
        // 保存到浏览器的localStorage中
        localStorage.setItem('user',JSON.stringify(user));
        localStorage.setItem('token',token);
    }
    let user = computed(()=>{
        // 在js中，空对象（{}）if判断为true
        // 空字符串（''）if判断为false
        if (Object.keys(_user.value).length === 0) {
            let user_str = localStorage.getItem('user');
            if (user_str) {
                _user.value = JSON.parse(user_str); 
            }
        }
        return _user.value
    })
    let token = computed(()=>{
        if (!_token.value) {
            let token_str = localStorage.getItem('token');
            if (token_str) {
                _token.value = token_str; 
            }
        }
        return _token.value
    })
    // 清除token
    function clearToken(){
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        _token.value = '';
        _user.value = {};
    }


    return {token,user,setUserToken,clearToken}
})
